# 编写用户相关的业务
from rest_framework.generics import ListCreateAPIView
from rest_framework.permissions import IsAdminUser
from apps.meiduo_admin.serializers.users import UserSerialzier
from apps.meiduo_admin.utils import NumPage
from apps.users.models import User


class UsersView(ListCreateAPIView):
    # 指定序列化器
    serializer_class = UserSerialzier
    # 指定查询集
    queryset = User.objects.filter(is_staff=False)
    # 指定权限
    permission_classes = [IsAdminUser]
    # 指定分页
    pagination_class = NumPage

    # 重写GenericAPIView类中的获取数据方法get_queryset
    def get_queryset(self):
        # 获取关键字keyword   keyword是查询字符串数据  request.query_params 获取查询字符串数据
        keyword = self.request.query_params.get('keyword')
        # 根据关键返回不同的数据内容
        if keyword == '' or keyword == None:
            return self.queryset
        else:
            return User.objects.filter(is_staff=False, username__contains=keyword) # contains 是否包含
